package connections;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;



public class HTTPDanoConnection extends Connection{
	String url;
	String fileType = "image/png";
	boolean readyForMore = true;
    HttpConnection c = null;
    byte[] outputArray;
    DataOutputStream dataOut = null;



	public HTTPDanoConnection(String _url, ConnectionListener _replyTo){
		url = _url;
		setAddress(url);
		mainProgram = _replyTo;
		mainProgram.connectionMade(this,_url);
	}
	
	/*public HTTPDanoConnection(String _url, ConnectionListener _replyTo, String _filename){
		url = _url;
		mainProgram = _replyTo;
		setFilename(_filename);
		//openConnection();
		mainProgram.connectionMade(this,_url);
	}*/
	
	public HTTPDanoConnection(String _url){
		setAddress(url);
		url = _url;
	}
	
	public boolean isReadyForMore(){
		return readyForMore ;
	}

/*
    public void openConnection(){
    	setAddress(url);
 	   try {
 	  c = (HttpConnection) Connector.open(url);

       c.setRequestMethod(HttpConnection.POST);
   
   		c.setRequestProperty("Content-Type", "multipart/form-data, boundary=AaB03x");
		dataOut = new DataOutputStream(c.openOutputStream());

		dataOut.write("--AaB03x\r\n".getBytes());
		dataOut.write(("Content-Disposition: form-data; name=\"image_file\"; filename=\"" + filename + "\"\r\n").getBytes());
		dataOut.write(("Content-Type: " + fileType + " \r\n").getBytes());
		dataOut.write("\r\n".getBytes());

 	   } catch (Exception e) {
             System.out.println("Problem with post " + e);
         }

 }*/
    
    public void send(byte[] _outputArray){
		try {
			dataOut.write(_outputArray);
			dataOut.flush();
		    //reply("ok");
		} catch (IOException e) {
			System.out.println("problem writing");
		}
    }
	public void send( byte[] _array, String _filename){
		String newFilename  = "";
		if (_filename != null){
			if (_filename.indexOf("%") == -1){
				newFilename = encode(_filename,"UTF-8");
			}else{
				newFilename = _filename;
			}
		}
		
	    new PostFile(_array, newFilename);
	}
	public void send( byte[] _array, String _filename, int _len){
		String newFilename  = "";
		if (_filename != null){
			if (_filename.indexOf("%") == -1){
				newFilename = encode(_filename,"UTF-8");
			}else{
				newFilename = _filename;
			}
		}
		
		
	    new PostFile(_array,newFilename,_len);
	}
	

	
    public void closeConnection(){
    	 System.out.println("Disconnecting" );
    	  String response = "Server Response:";
    	try{
    	dataOut.write("\r\n--AaB03x--\r\n".getBytes());
		dataOut.flush();

		dataOut.close();
		System.out.println("waiting for server");
        
	                //receive response and display in a text box.
        is = c.openDataInputStream();
    
        int ch;
      
      while ((ch = is.read()) != -1) {
          response = response + (char) ch;
        }
     // dataOut.close();
       is.close();
      c.close();
    
    } catch (Exception e) {
        System.out.println("Problem closing " + e);
    }
  //  System.out.println( " size:" + outputArray.length + " "+ response);
    	reply(response);
    }
    
 

	//public void send( byte[] _array){
	//		new PostFile(_array);
	//}
	

	//public void setFilename(String _s){
	//	filename = encode(_s,"UTF-8");
	//}
	public void setType(String _s){
		fileType = _s;
	}
	public void addListener(ConnectionListener _cl){
		mainProgram = _cl;
	}
	public void doGet(String _url){
		  new get(_url);
	}
	public void reply(String _s){
		
		  mainProgram.incoming(this, _s.getBytes()); 
	}
	class get extends Thread{

	    String getURL;
	    get(String _url){
	    	readyForMore = false;
	        this.start();
	    }
	    
	    public void run(){
	        //String postPicture(String url, byte[] outputArray) {
	            //should do this in a separate thread
	            HttpConnection c = null;
	            InputStream is = null;
	            OutputStream os = null;
	            String b = "Server Response:";
	          
	            try {
	                c = (HttpConnection) Connector.open(getURL);

	                c.setRequestMethod(HttpConnection.GET);
	            
	            	//c.setRequestProperty("Content-Type", "multipart/form-data, boundary=AaB03x");
	    		//	DataOutputStream dataOut = new DataOutputStream(c.openOutputStream());

	    			// dataOut.flush();

	    			//dataOut.close();
	    			System.out.println("waiting for server");
	                
	     	                //receive response and display in a text box.
	                is = c.openDataInputStream();
	                int ch;
	                while ((ch = is.read()) != -1) {
	                    b = b + (char) ch;
	                }
	               // dataOut.close();
	                c.close();
	            } catch (Exception e) {
	                System.out.println("Problem with post " + e);
	            }
	        
	          //  mainProgram.incoming(HTTPDanoConnection.this, b.getBytes());
	            System.out.println(b);
	          
	        }

	        
	    }
	
	
	class PostFile extends Thread{

		int length;
	    String filename;
	    
	    PostFile( byte[] _outputArray, String _filename){
	 
	        outputArray = _outputArray;
	        filename = _filename;
	        length = outputArray.length;
	        this.start();
	    }
	    
	    PostFile( byte[] _outputArray, String _filename, int _len){
	   	 
	        outputArray = _outputArray;
	        filename = _filename;
	        length = _len;
	        this.start();
	    }
	    
	   
	    public void run(){
	        //String postPicture(String url, byte[] outputArray) {
	            //should do this in a separate thread

	            InputStream is = null;
	            String response = "Server Response:";

	            System.out.println("filename "+ filename);
	            try {
	                c = (HttpConnection) Connector.open(url);

	                c.setRequestMethod(HttpConnection.POST);
	            
	            	c.setRequestProperty("Content-Type", "multipart/form-data, boundary=AaB03x");
	            //	c.setRequestProperty("content-length", "" + (boundaryMessageBytes.length + outputArray.length + endBoundary.length())); 
	            	dataOut = new DataOutputStream(c.openOutputStream());

	    			dataOut.write("--AaB03x\r\n".getBytes());
	    			//dataOut.write(("Content-Disposition: form-data; name=\"image_file\"; filename=\"" + filename + "\"\r\n").getBytes());

	    			dataOut.write(("Content-Disposition: form-data; name=\"data_file\"; filename=\"" + filename + "\"\r\n").getBytes());
	    			dataOut.write(("Content-Type: " + fileType + " \r\n").getBytes());
	    			dataOut.write("\r\n".getBytes());
	    			dataOut.write(outputArray,0,length);
	    		
	    			dataOut.write("\r\n--AaB03x--\r\n".getBytes());
	    			dataOut.flush();

	    			dataOut.close();
	    			System.out.println("waiting for server");
	                
	     	                //receive response and display in a text box.
	                is = c.openDataInputStream();
	                int ch;
	                while ((ch = is.read()) != -1) {
	                    response = response + (char) ch;
	                }
	                dataOut.close();
	                c.close();
	            } catch (Exception e) {
	                System.out.println("Problem with post " + e);
	            }

	            System.out.println( " size:" + outputArray.length + " "+ response);
	            reply(response);
	            readyForMore = true;
	        }

	        
	    }
	
    /* this function was taken from the Java forums, at
    * http://forum.java.sun.com/thread.jspa?forumID=76&messageID=624066&threadID=178903
    * and modified to behave like the original one.
    * @param s string to encode
    * @param enc normally, this would be "UTF8", but here it is ignored.
    * @throws IOException on  IO error
    * @return an encoded version of the string <CODE>s</CODE>
    */
   public String encode(String s, String enc){
	   StringBuffer ret = new StringBuffer(); //return value

	   try{
     ByteArrayOutputStream bOut = new ByteArrayOutputStream();
     DataOutputStream dOut = new DataOutputStream(bOut);
        dOut.writeUTF(s);
     ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
     bIn.read();
     bIn.read();
     int c = bIn.read();
     while (c >= 0) {
       if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
       || (c >= '0' && c <= '9') || c == '.' || c == '-' || c == '*' || c == '_')
         ret.append((char)c);
       else if (c == ' ')
         ret.append('+');
       else {
         if (c < 128) {
           appendHex(c, ret);
         } else if (c < 224) {
           appendHex(c, ret);
           appendHex(bIn.read(), ret);
         } else if (c < 240) {
           appendHex(c,ret);
           appendHex(bIn.read(), ret);
           appendHex(bIn.read(), ret);
         }

       }
       c = bIn.read();

     }
	   }catch(IOException e){
		   System.out.println("hey");
		   mainProgram.feedback(HTTPDanoConnection.this,"Error Encoding");
	   }
     return ret.toString();
   }

   private void appendHex(int arg0, StringBuffer buff){
     buff.append('%');
     if (arg0 < 16)
       buff.append('0');
     buff.append(Integer.toHexString(arg0));
   }
}
